package com.cci.kangdao.utilTool;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.dao.model.UserT;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class GDRegion {

	private final static Logger LOG = Logger.getLogger(GDRegion.class);

	@Deprecated
	public static Map<String, Object> getReginInfo(String address) {
		String url = "http://restapi.amap.com/v3/geocode/geo?key=9446552667cc1163788c780833dd282d&address=" + address;
		JSONObject jo = JSONObject.fromObject(JSONArray.fromObject(JSONObject.fromObject(GDRegion.loadJSON(url)).get("geocodes")).get(0));
		Map<String, Object> map = new HashMap<>();
		map.put("province", jo.get("province"));
		map.put("city", jo.get("city"));
		map.put("area", jo.get("district"));
		return map;
	}

	public static Map<String,Object> getAddressInfo(String address){
		Map<String,Object> addressInfoMap = new HashMap<>(4);
		try {
			if(StringUtils.isNotEmpty(address)){
				address  = URLEncoder.encode(address,"UTF-8");
				String url = String.format("%s?key=%s&address=%s","https://restapi.amap.com/v3/geocode/geo",PropertiesUtil.getProperties("projectconfig.properties","Golden.GoldenKey"),address);
				String response = HttpUtils.get(url,new ResponseHandler<String>() {
					@Override
					public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
						if (response.getStatusLine().getStatusCode() == 200) {
							HttpEntity httpEntity = response.getEntity();
							return  EntityUtils.toString(httpEntity);
						}
						return null;
					}
				});
				String requestLog = String.format("访问高德获取地址信息，请求：%s,响应：%s",url,response);
				LOG.info(requestLog);
				if(StringUtils.isNotEmpty(response)){
					try {
						JSONObject jsonObject = (JSONObject) JSONObject.fromObject(response).getJSONArray("geocodes").get(0);
						String province = jsonObject.getString("province");
						String city = jsonObject.getString("city");
						String district = jsonObject.getString("district");
						String location = jsonObject.getString("location");
						String adCode = jsonObject.getString("adcode");
						String[] lonLat = location.split(",");
						String longitude = lonLat[0];
						String latitude = lonLat[1];
						addressInfoMap.put("province",province);
						addressInfoMap.put("city",city);
						addressInfoMap.put("area",district);
						addressInfoMap.put("longitude",longitude);
						addressInfoMap.put("latitude",latitude);
						addressInfoMap.put("adCode",adCode);
					} catch (Exception e) {
						LOG.error("高德获取地址信息发生异常，异常："+e+"；response："+response);
					}
				}
			}
		} catch (Exception e) {
			LOG.error("高德获取地址信息发生异常，异常："+e);
		}
		return addressInfoMap;
	}

	/**
	 * 通过起止经纬点，获取规划路线的距离和市场
	 * @param originLon 起始经度
	 * @param originLat 起始纬度
	 * @param destLon 目的经度
	 * @param destLat 目的纬度
	 * @return map distance:距离（米）；duration：耗时（秒）；
	 */
	public static Map<String,Object> direction(String originLon,String originLat,String destLon,String destLat){
		return direction(DirectionType.SHORTEST,originLon,originLat,destLon,destLat);
	}

	public static Map<String,Object> direction(DirectionType directionType,String originLon,String originLat,String destLon,String destLat){
		Map<String,Object> directionMap = new HashMap<>(2);
		Map<String,String> parameterMap = new HashMap<>();
		parameterMap.put("key",PropertiesUtil.getProperties("projectconfig.properties","Golden.GoldenKey"));
		String filterOriginLon = filterLatAndLon(originLon);
		String filterOriginLat = filterLatAndLon(originLat);
		parameterMap.put("origin",String.format("%s,%s",filterOriginLon,filterOriginLat));
		String filterDestLon = filterLatAndLon(destLon);
		String filterDestLat = filterLatAndLon(destLat);
		parameterMap.put("destination",String.format("%s,%s",filterDestLon,filterDestLat));
		//0：最快捷模式
		//		//1：最经济模式
		//		//2：最少换乘模式
		//		//3：最少步行模式
		//		//5：不乘地铁模式
		if(DirectionType.FASTEST.equals(directionType)){
			parameterMap.put("strategy","0");
		}else if (DirectionType.AVOID_CONGESTION.equals(directionType)){
			parameterMap.put("strategy","4");
		}else{
			parameterMap.put("strategy","2");
		}
		String url = HttpUtils.createUrlWithParameters("https://restapi.amap.com/v3/direction/driving",parameterMap);
		String response = HttpUtils.get(url,new ResponseHandler<String>() {
			@Override
			public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
				if (response.getStatusLine().getStatusCode() == 200) {
					HttpEntity httpEntity = response.getEntity();
					return  EntityUtils.toString(httpEntity);
				}
				return null;
			}
		});
		String requestLog = String.format("访问高德获取路径规划信息，请求：%s,响应：%s",url,response);
		LOG.info(requestLog);
		if(StringUtils.isNotEmpty(response)){
			try {
				JSONObject jsonObject = JSONObject.fromObject(response);
				Integer status = jsonObject.getInt("status");
				if(status.equals(1)){
					JSONObject route = jsonObject.getJSONObject("route");
					JSONObject path = (JSONObject) route.getJSONArray("paths").get(0);
					directionMap.put("distance",path.getString("distance"));
					directionMap.put("duration",path.getString("duration"));
				}else{
					LOG.error("高德获取规划方案发生错误，response："+response);
				}
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error("高德获取地址信息发生异常，异常："+e+"；response："+response);
			}

		}
		return directionMap;
	}

	private static String filterLatAndLon(String latOrLon){
		BigDecimal latOrLonDecimal = NumberUtils.createBigDecimal(latOrLon);
		return String .format("%.6f",latOrLonDecimal);
	}

	@Deprecated
	public static Map<String, Object> getReginInfo(String positionLat, String positionLon) {
		if(StringUtils.isEmpty(positionLon) || StringUtils.isEmpty(positionLat)) 
			return null;

		String key = PropertiesUtil.getProperties("projectconfig.properties","Golden.GoldenKey");
		String url = "http://restapi.amap.com/v3/geocode/regeo?key="+key+"&location=" + positionLon + "," + positionLat;
		String areaStr = GDRegion.loadJSON(url);
		LOG.info("高德请求的返回值:" +areaStr);
		if (areaStr.isEmpty() || areaStr.equals("")){

			return null;
		}

		JSONObject areaJo = JSONObject.fromObject(areaStr);
		if (areaJo.isEmpty() || areaJo == null){

			return null;
		}
		String regeocodeStr = areaJo.get("regeocode").toString();
		if (regeocodeStr.isEmpty() || regeocodeStr.equals("")){

			return null;
		}
		JSONObject regeocodeJo = JSONObject.fromObject(regeocodeStr);
		if (regeocodeJo.isEmpty() || regeocodeJo == null){

			return null;
		}
		String addressComponentStr = regeocodeJo.get("addressComponent").toString();
		if (addressComponentStr.isEmpty() || addressComponentStr.equals("")){

			return null;
		}

		JSONObject jo = JSONObject.fromObject(addressComponentStr);
		Map<String, Object> map = new HashMap<>();
		map.put("province", jo.get("province").toString());
		map.put("location",regeocodeJo.get("formatted_address"));
//		try {
//			map.put("province", URLEncoder.encode(jo.get("province").toString(), "UTF-8"));
//		} catch (UnsupportedEncodingException e) {
//			map.put("province", CRMServiceConst.PROVICE_DEFAULT);
//			e.printStackTrace();
//		}
		if(jo.get("city") instanceof JSONArray) {
			String code = (String)jo.get("adcode");
			if(code.indexOf("1101") == 0) {
				map.put("city", "北京城区");
				String area = (jo.get("district") instanceof JSONArray?jo.get("township"):jo.get("district")).toString();
				map.put("area",area);
//				try {
//					map.put("area", URLEncoder.encode(area, "UTF-8"));
//				} catch (UnsupportedEncodingException e) {
//					map.put("area", CRMServiceConst.AREA_DEFAULT);
//					e.printStackTrace();
//				}
			} else if(code.indexOf("1201") == 0) {
				map.put("city", "天津城区");
				String area = (jo.get("district") instanceof JSONArray?jo.get("township"):jo.get("district")).toString();
				map.put("area", area);
//				try {
//					map.put("area", URLEncoder.encode(area, "UTF-8"));
//				} catch (UnsupportedEncodingException e) {
//					map.put("area", CRMServiceConst.AREA_DEFAULT);
//					e.printStackTrace();
//				}
			} else if(code.indexOf("3101") == 0) {
				map.put("city", "上海城区");
				String area = (jo.get("district") instanceof JSONArray?jo.get("township"):jo.get("district")).toString();
				map.put("area", area);
//				try {
//					map.put("area", URLEncoder.encode(area, "UTF-8"));
//				} catch (UnsupportedEncodingException e) {
//					map.put("area", CRMServiceConst.AREA_DEFAULT);
//					e.printStackTrace();
//				}
			} else if(code.indexOf("5001") == 0) {
				map.put("city", "重庆城区");
				String area = (jo.get("district") instanceof JSONArray?jo.get("township"):jo.get("district")).toString();
				map.put("area", area);
//				try {
//					map.put("area", URLEncoder.encode(area, "UTF-8"));
//				} catch (UnsupportedEncodingException e) {
//					map.put("area", CRMServiceConst.AREA_DEFAULT);
//					e.printStackTrace();
//				}
			} else if(code.indexOf("5002") == 0) {
				map.put("city", "重庆郊县");
				String area = (jo.get("district") instanceof JSONArray?jo.get("township"):jo.get("district")).toString();
				map.put("area", area);
//				try {
//					map.put("area", URLEncoder.encode(area, "UTF-8"));
//				} catch (UnsupportedEncodingException e) {
//					map.put("area", CRMServiceConst.AREA_DEFAULT);
//					e.printStackTrace();
//				}
			} else {
				if(!(jo.get("district") instanceof JSONArray) && !(jo.get("township") instanceof JSONArray)) {
					map.put("city", jo.get("district").toString());
					map.put("area", jo.get("township").toString());
//					try {
//						map.put("city", URLEncoder.encode(jo.get("district").toString(), "UTF-8"));
//						map.put("area", URLEncoder.encode(jo.get("township").toString(), "UTF-8"));
//					} catch (UnsupportedEncodingException e) {
//						map.put("city", CRMServiceConst.CITY_DEFAULT);
//						map.put("area", CRMServiceConst.AREA_DEFAULT);
//						e.printStackTrace();
//					}
				}
			}
		} else {
			map.put("city", jo.get("city").toString());
			map.put("area", (jo.get("district") instanceof JSONArray?jo.get("township"):jo.get("district")).toString());
//			try {
//				map.put("city", URLEncoder.encode(jo.get("city").toString(), "UTF-8"));
//				map.put("area", URLEncoder.encode((jo.get("district") instanceof JSONArray?jo.get("township"):jo.get("district")).toString(), "UTF-8"));
//			} catch (UnsupportedEncodingException e) {
//				map.put("city", CRMServiceConst.CITY_DEFAULT);
//				map.put("area", CRMServiceConst.AREA_DEFAULT);
//				e.printStackTrace();
//			}
		}
		LOG.info("经纬度转化省市县:" + JsonUtils.toJsonString(map));
		return map;
	}

	/**
	 * 根据IP，调用高德的根据IP获取位置的接口，并将user赋值
	 *
	 * @param ip
	 * @param userT
	 * @return
	 */
	public static UserT addProviceAndCity(String ip, UserT userT) {
		String key = PropertiesUtil.getProperties("projectconfig.properties", "Golden.GoldenKey");
		String url = "https://restapi.amap.com/v3/ip?key=" + key + "&ip=" + ip;
		String areaStr = GDRegion.loadJSON(url);
		LOG.info("addProviceAndCity----" + ip + areaStr);
		String status = JSON.parseObject(areaStr).getString("status");
		if (StringUtils.isNotBlank(status) && "1".equals(status)) {
			String province = JSON.parseObject(areaStr).getString("province");
			String city = JSON.parseObject(areaStr).getString("city");
			userT.setProvince(province);
			userT.setCity(city);
			userT.setIp(ip);
		}
		return userT;
	}


	public static String loadJSON(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL oracle = new URL(url);
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					yc.getInputStream(), "UTF-8"));
			String inputLine = null;
			while ( (inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
		return json.toString();
	}
	
	public static void main(String[] args) {
//		GDRegion.getReginInfo("浙江省台州市玉环县城关三合潭西山村");
//		Map<String,Object> map = GDRegion.getReginInfo("35.0912022310633", "112.614323665965");
//		System.out.println(map);
		//GDRegion.direction();
		//120.067522	43.874535
		Map<String, Object> reginInfo = getReginInfo("43.874535", "120.067522");
		System.out.println(reginInfo.toString());
	}

	public static enum DirectionType{
		FASTEST,SHORTEST,AVOID_CONGESTION
	}

}
